﻿//========================================================================
// *作者：海盗猫  主页：ilplay.com
// *脚本：EditorSearchPage
// *描述：EditorSearchPage
// *?2024 HDMCode . All rights reserved.
//* ======================================================================
using System.Collections.Generic;
using System.IO;
using HDMCode.FrameEditor;
using HDMCode.UIFrame;
using Unity.CodeEditor;
using UnityEditor;
using UnityEngine;

namespace HDMCode.UIFrameEditor
{
    public class EditorSearchPage : EditorWindow
    {
        /// <summary>
        /// 当前编辑器窗口
        /// </summary>
        private static EditorSearchPage m_ThisWindow { get; set; }

        /// <summary>
        /// 当前搜索窗口缓存
        /// </summary>
        private Dictionary<string, Dictionary<string, EditorSearchDate>> m_SearchCache;
        
        /// <summary>
        /// 当前搜索窗口滚动栏
        /// </summary>
        private static Vector2 m_PreviewScroll;

        /// <summary>
        /// 搜索窗口初始化
        /// </summary>
        public void OnEnable()
        {
            m_ThisWindow ??= this;
            HDMEditorStyle.InitStyle();
            SearchAssets();
        }
        
        /// <summary>
        /// 绘制搜索窗口
        /// </summary>
        public void OnGUI()
        {
            m_PreviewScroll = GUILayout.BeginScrollView(m_PreviewScroll, GUILayout.ExpandWidth(true),GUILayout.ExpandHeight(true));
            foreach (var groupItem in m_SearchCache)
            {
                HDMEditorHelper.DrawTileLable($"分组：{groupItem.Key}");
                foreach (var prefabItem in groupItem.Value)
                {
                    using (new UnityEditor.EditorGUILayout.HorizontalScope())
                    {
                        GUILayout.Space(20);
                        GUILayout.Label($"[ {prefabItem.Value.FileName} ]", HDMEditorStyle.styleCheckText,GUILayout.Width(140), GUILayout.Height(20));
                        GUILayout.Label($"{prefabItem.Value.PrefabInfo?.Describe}");
                        var assetPath = EditorMenu.Handle.GetPath(prefabItem.Value?.PrefabInfo,EditorBaseDate.FileType.Asset);
                        var scriptPath = EditorMenu.Handle.GetPath(prefabItem.Value?.PrefabInfo,EditorBaseDate.FileType.Script);
                        if (prefabItem.Value!=null)
                        {
                            CheckPrefab(assetPath,prefabItem.Value.PrefabInfo);
                            CheckScript(assetPath,scriptPath,prefabItem.Value.PrefabInfo);
                            CheckHistory(assetPath,scriptPath,prefabItem.Value,prefabItem.Value.PrefabInfo);
                            RemoveAssets(assetPath,scriptPath,prefabItem.Value.PrefabInfo);
                        }
                    }
                }
            }
            GUILayout.EndScrollView();
        }

        /// <summary>
        /// 检测预制件
        /// </summary>
        /// <param name="assetPath">预制件资源路径信息</param>
        /// <param name="creatDate">创建信息</param>
        public void CheckPrefab((string groupPath,string floderPath,string filePath,string genFilePath) assetPath,EditorCreatDate creatDate)
        {
            if (File.Exists(assetPath.filePath))
            {
                HDMEditorHelper.DrawButton("预制体", "CorrectIcon.png",new[] { GUILayout.Height(20), GUILayout.Width(90) },
                    () =>
                    {
                        HDMEditorHelper.SeletFile(EditorHelper.SystemPathChangeProjectPath(assetPath.filePath));
                        SearchAssets();
                    });
            }
            else
            {
                HDMEditorHelper.DrawButton("预制体", "ErrorIcon.png",new[] { GUILayout.Height(20), GUILayout.Width(90) },
                    () =>
                    {
                        if (EditorUtility.DisplayDialog("提示：", "是否立即修复预制件资源", "立即修复", "取消"))
                        {
                            EditorMenu.Handle.CheckFloder(creatDate, out _, true);
                            EditorMenu.Handle.CreatPrefabAssets(creatDate);
                            AssetDatabase.Refresh();
                            HDMEditorHelper.SeletFile(EditorHelper.SystemPathChangeProjectPath(assetPath.filePath));
                        }
                        else
                            HDMEditorHelper.SeletFile(EditorHelper.SystemPathChangeProjectPath(assetPath.floderPath));
                        SearchAssets();
                    });
            }
        }

        /// <summary>
        /// 检测脚本资源
        /// </summary>
        /// <param name="assetPath">预制件资源路径信息</param>
        /// <param name="scriptPath">脚本资源路径信息</param>
        /// <param name="creatDate">创建信息</param>
        public void CheckScript((string groupPath,string floderPath,string filePath,string genFilePath) assetPath,(string groupPath,string floderPath,string filePath,string genFilePath) scriptPath,EditorCreatDate creatDate)
        {
            if (File.Exists(scriptPath.filePath) && File.Exists(scriptPath.genFilePath))
            {
                HDMEditorHelper.DrawButton("编辑脚本", "CorrectIcon.png",new[] { GUILayout.Height(20), GUILayout.Width(90) },
                    () =>
                    {
                        CodeEditor.CurrentEditor.OpenProject(EditorHelper.SystemPathChangeProjectPath(scriptPath.filePath));
                    });
            }
            else
            {
                HDMEditorHelper.DrawButton("丢失脚本", "ErrorIcon.png",new[] { GUILayout.Height(20), GUILayout.Width(90) },
                    () =>
                    {
                        if (File.Exists(assetPath.filePath))
                        {
                            Debug.Log(assetPath.filePath);
                            GameObject prefab = AssetDatabase.LoadAssetAtPath<GameObject>(EditorHelper.SystemPathChangeProjectPath(assetPath.filePath));
                            UIDisplay uiDisplay = prefab.GetComponent<UIDisplay>();
                            if (!File.Exists(scriptPath.filePath))
                                EditorMenu.Handle.CreatScriptAssets(creatDate,uiDisplay.components,EditorBaseDate.ScriptType.Lift);
                            if (!File.Exists(scriptPath.genFilePath))
                                EditorMenu.Handle.CreatScriptAssets(creatDate,uiDisplay.components,EditorBaseDate.ScriptType.Gen);
                            HDMEditorHelper.SeletFile(EditorHelper.SystemPathChangeProjectPath(scriptPath.groupPath));
                        }
                        else
                        {
                            EditorUtility.DisplayDialog("提示：", "获取资源文件失败!", "好的");
                            HDMEditorHelper.SeletFile(EditorHelper.SystemPathChangeProjectPath(assetPath.filePath));
                        }
                        SearchAssets();
                    });
            }
        }

        /// <summary>
        /// 检测历史资源
        /// </summary>
        /// <param name="assetPath">预制件资源路径信息</param>
        /// <param name="scriptPath">脚本资源路径信息</param>
        /// <param name="searchDate">搜索缓存</param>
        /// <param name="creatDate">创建信息</param>
        public void CheckHistory((string groupPath,string floderPath,string filePath,string genFilePath) assetPath,(string groupPath,string floderPath,string filePath,string genFilePath) scriptPath,EditorSearchDate searchDate,EditorCreatDate creatDate)
        {
            if (searchDate != null && searchDate.IsFileExist)
            {
                HDMEditorHelper.DrawButton("历史记录", "CorrectIcon.png",new[] { GUILayout.Height(20), GUILayout.Width(90) },
                    () =>
                    {
                        HDMEditorHelper.SeletFile(EditorHelper.SystemPathChangeProjectPath(assetPath.groupPath));
                        SearchAssets();
                    });
            }
            else
            {
                HDMEditorHelper.DrawButton("历史记录", "ErrorIcon.png",new[] { GUILayout.Height(20), GUILayout.Width(90) },
                    () =>
                    {
                        if (File.Exists(assetPath.filePath) && File.Exists(scriptPath.genFilePath) &&File.Exists(scriptPath.filePath))
                        {
                            creatDate.Guid = AssetDatabase.AssetPathToGUID(EditorHelper.SystemPathChangeProjectPath(assetPath.filePath));
                            EditorMenu.Handle.AddInfoToSetting(creatDate);
                            AssetDatabase.Refresh();
                            SearchAssets();
                        }
                        else
                            EditorUtility.DisplayDialog("提示：", "添加失败，需要优先修复其它异常选项!", "好的");
                    });
            }
        }

        /// <summary>
        /// 移除资源
        /// </summary>
        /// <param name="assetPath">预制件资源路径信息</param>
        /// <param name="scriptPath">脚本资源路径信息</param>
        /// <param name="creatDate">创建信息</param>
        public void RemoveAssets((string groupPath,string floderPath,string filePath,string genFilePath) assetPath,(string groupPath,string floderPath,string filePath,string genFilePath) scriptPath,EditorCreatDate creatDate)
        {
            HDMEditorHelper.DrawButton("移除", "Remove.png",new[] { GUILayout.Height(20), GUILayout.Width(90) }, () =>
                {
                    if (EditorUtility.DisplayDialog("提示：", "立即删除将会移除当前所有UI资源及其子资源，是否立即删除!", "立即删除","取消"))
                    {
                        if (Directory.Exists(assetPath.floderPath))
                            AssetDatabase.DeleteAsset(EditorHelper.SystemPathChangeProjectPath(assetPath.floderPath));

                        if (Directory.Exists(scriptPath.floderPath))
                            AssetDatabase.DeleteAsset(EditorHelper.SystemPathChangeProjectPath(scriptPath.floderPath));
                    
                        Debug.Log(creatDate.CreatName);
                        EditorMenu.Handle.RemoveInfoToSetting(creatDate);
                        AssetDatabase.Refresh();
                    }
                    SearchAssets();
                });
        }

        /// <summary>
        /// 搜索所有文件夹和设置中存在的资源配置
        /// </summary>
        public void SearchAssets()
        {
            m_SearchCache = new();
            DirectoryInfo prefabFiles = new DirectoryInfo(EditorBaseDate.Setting.AssetsPath);
            foreach (var groupItem in prefabFiles.GetDirectories())
            {
                var listPrefab = new Dictionary<string, EditorSearchDate>();
                foreach (var prefabItem in groupItem.GetDirectories())
                {
                    var searchDate = new EditorSearchDate(prefabItem.Name);
                    if (EditorHelper.ContainsSetting(prefabItem.Name, out var assetsInfo))
                    {
                        searchDate.PrefabInfo = assetsInfo;
                        searchDate.IsFileExist = true;
                    }
                    else
                        searchDate.PrefabInfo = new EditorCreatDate()
                            { CreatName = prefabItem.Name, Group = EditorMenu.Handle.GetGroupIndex(groupItem.Name) };

                    listPrefab.Add(searchDate.FileName, searchDate);
                }

                m_SearchCache.Add(groupItem.Name, listPrefab);
            }

            foreach (var settings in EditorBaseDate.Setting.UISettings)
            {
                if (m_SearchCache.TryGetValue(EditorBaseDate.Setting.Groups[settings.Group], out var item))
                {
                    if (!item.ContainsKey(settings.CreatName))
                    {
                        var searchDate = new EditorSearchDate(settings.CreatName);
                        searchDate.PrefabInfo = settings;
                        searchDate.IsFileExist = true;
                        item.Add(settings.CreatName, searchDate);
                    }
                }
            }
        }
    }
}